package org.hang.gift.controller;


import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.hang.util.AjaxResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/aliyun/oss")
public class AliyunOssController {


    /**
     * 通过id和secret去aliyun oss 拿到一个签名，将签名 返回给 前端
     * @return
     */
    @GetMapping("/sign")
    public AjaxResult getSign(){

        String endpoint = "oss-cn-chengdu.aliyuncs.com";
        // 填写Bucket名称，例如examplebucket。
        String bucket = "gift-hang";
        // 填写Host名称，格式为https://桶名.endpoint。
        String host = "https://"+bucket+"."+endpoint;
        // 子账号的id
        String accessKeyId = "LTAI5tRVEcpoardqGFM6Jgck";
        String accessKeySecret = "VVncZWWC8pc1SsaixRiHWIP3WlMejI";

        // 设置上传到OSS文件的前缀，可置空此项。置空后，文件将上传至Bucket的根目录下。
        String dir = "images/";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");

            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            // 这个map是要返回给前端的
            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessId", accessKeyId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);    // 签名
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            // respMap.put("expire", formatISO8601Date(expiration));

            return AjaxResult.me().setResultObj(respMap);
        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
            return AjaxResult.me().setSuccess(false).setMessage("获取签名失败!");
        } finally {
            ossClient.shutdown();
        }
    }

    /**
     * 删除文件，通过请求对象接收，请求对象的 请求头 中有图片的地址
     * @param request
     * @return
     */
    @DeleteMapping("/delete")
    public AjaxResult delete(HttpServletRequest request) {
        String endpoint = "https://oss-cn-chengdu.aliyuncs.com";
        String bucketName = "gift-hang";
        // 图片地址的前缀
        String prefix = "https://" + bucketName + "." + "oss-cn-chengdu.aliyuncs.com" + "/";
        //获取图片地址
        String url = request.getHeader("deleteUrl");
        //将前缀清空，剩下的就是文件名称
        String objectName = url.replace(prefix, "");
        String accessKeyId = "LTAI5tRVEcpoardqGFM6Jgck";
        String accessKeySecret = "VVncZWWC8pc1SsaixRiHWIP3WlMejI";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            //删除 Bucket名称为bucketName 中的 文件名 为objectName的文件
            ossClient.deleteObject(bucketName, objectName);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
            return AjaxResult.me().setSuccess(false).setCode(500).setMessage(oe.getMessage());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
            return AjaxResult.me().setSuccess(false).setCode(500).setMessage(ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return AjaxResult.success();
    }

}
